import 'package:get/get.dart';

import 'package:get_storage/get_storage.dart';
import 'package:grab_the_order/app/modules/rule_model.dart';
import 'package:uuid/uuid.dart'; // 需要添加 uuid 库

class RuleService extends GetxService {
  final _box = GetStorage();
  final _uuid = const Uuid();
  final String _storageKey = 'rules';

  // 存储所有规则的响应式列表
  final RxList<RuleModel> rules = <RuleModel>[].obs;

  @override
  void onInit() {
    super.onInit();
    _loadRules();
  }

  // 从本地存储加载规则到内存
  void _loadRules() {
    List<dynamic>? storedRules = _box.read<List<dynamic>>(_storageKey);
    if (storedRules != null) {
      rules.value = storedRules
          .map((ruleMap) =>
              RuleModel.fromMap(Map<String, dynamic>.from(ruleMap)))
          .toList();
    }
  }

  // 保存所有规则到本地存储
  Future<void> _saveRules() async {
    await _box.write(_storageKey, rules.map((rule) => rule.toMap()).toList());
  }

  // 添加一条新规则
  Future<void> addRule(RuleModel rule) async {
    // 如果没有ID，则生成一个
    if (rule.id.isEmpty) {
      rule.id = _uuid.v4();
    }
    rules.add(rule);
    await _saveRules();
  }

  // 更新一条规则
  Future<void> updateRule(RuleModel updatedRule) async {
    int index = rules.indexWhere((rule) => rule.id == updatedRule.id);
    if (index != -1) {
      rules[index] = updatedRule;
      await _saveRules();
    }
  }

  // 删除一条规则
  Future<void> deleteRule(String id) async {
    rules.removeWhere((rule) => rule.id == id);
    await _saveRules();
  }

  // 【核心】规则匹配引擎
  // orderData 示例: {'amount': 35.5, 'distance': 8.0}
  bool evaluate(Map<String, dynamic> orderData, TargetApp app) {
    // 遍历所有已启用的、匹配当前APP的规则
    for (final rule in rules.where((r) => r.isEnabled && r.targetApp == app)) {
      // 假设只要有一条规则匹配成功，就返回 true
      if (_isRuleMatched(orderData, rule)) {
        print("订单匹配成功! 规则ID: ${rule.id}");
        return true;
      }
    }
    print("订单不符合任何规则，已忽略。");
    return false;
  }

  bool _isRuleMatched(Map<String, dynamic> orderData, RuleModel rule) {
    bool isMatch = true;

    // 检查滴滴规则
    if (rule.targetApp == TargetApp.didi) {
      // 检查最小金额
      if (rule.minAmount != null && orderData['amount'] != null) {
        if (orderData['amount'] < rule.minAmount!) {
          isMatch = false;
        }
      }
      // 检查最大路程
      if (rule.maxDistance != null && orderData['distance'] != null) {
        if (orderData['distance'] > rule.maxDistance!) {
          isMatch = false;
        }
      }
    }

    // 未来在这里扩展美团或其他APP的规则检查
    // ...

    return isMatch;
  }
}
